package parser;

import antlr.RecognitionException;
import java.util.*;

class IfStmt extends Stmt {
    
    Expr cond; 
    Stmt suite;
    Stmt _else = null;
    List<IfPart> ifs = new ArrayList<IfPart>();
    
    IfStmt(Expr cond, Stmt suite) {
        this.cond = cond;
        this.suite = suite;
        yields = suite.yields;
        deletes = suite.deletes;
    }
    
    void addIf(Expr cond, Stmt suite, int line) {
        ifs.add(new IfPart(cond, suite, line));
        yields |= suite.yields;
        deletes |= suite.deletes;
    }
    
    void addElse(Stmt suite) {
        _else = suite;
        yields |= suite.yields;
        deletes |= suite.deletes;
    }
    
    void write(ByteStream out) throws RecognitionException {
        out.line(line);
        List<Patch> patches = new ArrayList<Patch>();
//        out.write(Opcodes.IF);
        Patch next = cond.branch(false, out);
        suite.write(out);
        for(IfPart ip: ifs) {
            patches.add(out.branch(Opcodes.DONE_IF));
            out.line(ip.line);
            next.patch(out);
            next = ip.cond.branch(false, out);
            ip.suite.write(out);
        }
        
        if (_else != null) {
            patches.add(out.branch(Opcodes.DONE_IF));
            next.patch(out);
            out.line(_else.line);
            _else.write(out);
        } else {
             next.patch(out);  
        }
        for (Patch p: patches) {
            p.patch(out);
        }
    }
    
}

class IfPart {    
    
    Expr cond; 
    Stmt suite;
    int line;
    
    IfPart(Expr cond, Stmt suite, int line) {
        this.cond = cond;
        this.suite = suite;
        this.line = line;
    }

}
